<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select
            v-model="searchForm.userType"
            placeholder="请选择用户类型"
            clearable
          >
            <el-option label="普通用户" value="normal" />
            <el-option label="商家" value="merchant" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="黑名单状态">
          <el-select
            v-model="searchForm.blacklistStatus"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="正常" value="normal" />
            <el-option label="已拉黑" value="blacklisted" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search"></i> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <i class="fas fa-redo"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="list-card">
      <div class="toolbar">
        <div class="right">
          <el-button-group>
            <el-button type="primary" @click="handleAdd">
              <i class="fas fa-plus"></i> 新增用户
            </el-button>
            <el-button type="success" @click="handleBatchEnable">
              <i class="fas fa-check"></i> 批量启用
            </el-button>
            <el-button type="danger" @click="handleBatchDisable">
              <i class="fas fa-ban"></i> 批量禁用
            </el-button>
            <el-button type="info" @click="exportData">
              <i class="fas fa-download"></i> 导出数据
            </el-button>
          </el-button-group>
        </div>
      </div>

      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        border
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无用户数据" 
              :image-size="200"
            >
              <div class="empty-text">尚未有用户注册</div>
              <div class="empty-subtext">您可以添加用户或等待用户自行注册</div>
              <el-button type="primary" @click="handleAdd" class="mt-4">新增用户</el-button>
            </el-empty>
          </div>
        </template>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="scope">
            <div class="user-info">
              <el-avatar 
                :size="40" 
                :src="scope.row.avatar || '/images/default-avatar.png'"
                @error="() => handleAvatarError(scope.row)"
              />
              <div class="info-content">
                <div class="username">{{ scope.row.username }}</div>
                <div class="nickname text-gray-500 text-sm">
                  {{ scope.row.nickname }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column prop="userType" label="用户类型" width="100">
          <template #default="scope">
            <el-tag :type="getUserTypeTag(scope.row.userType)">
              {{ getUserTypeLabel(scope.row.userType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="blacklistStatus" label="黑名单状态" width="120">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.blacklistStatus === 'blacklisted'
                  ? 'danger'
                  : 'success'
              "
            >
              {{
                scope.row.blacklistStatus === "blacklisted" ? "已拉黑" : "正常"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="注册时间"
          width="180"
          sortable="custom"
        />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                :type="
                  scope.row.blacklistStatus === 'blacklisted'
                    ? 'success'
                    : 'danger'
                "
                size="small"
                @click="handleBlacklist(scope.row)"
              >
                {{
                  scope.row.blacklistStatus === "blacklisted"
                    ? "解除拉黑"
                    : "加入黑名单"
                }}
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="showDetail(scope.row)"
              >
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="userForm.userType" placeholder="请选择用户类型">
            <el-option label="普通用户" value="normal" />
            <el-option label="商家" value="merchant" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="'active'"
            :inactive-value="'disabled'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="用户详情"
      width="800px"
      class="user-detail-dialog"
    >
      <el-tabs v-model="activeDetailTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <div class="user-profile">
            <div class="profile-header">
              <div class="avatar-section">
                <el-avatar :size="100" :src="currentUser.avatar" />
                <div class="user-status" :class="currentUser.status">
                  {{ currentUser.status === "active" ? "正常" : "禁用" }}
                </div>
              </div>
              <div class="basic-info">
                <h3 class="username">{{ currentUser.username }}</h3>
                <div class="user-type">
                  <el-tag :type="getUserTypeTag(currentUser.userType)">
                    {{ getUserTypeLabel(currentUser.userType) }}
                  </el-tag>
                </div>
                <div class="user-id">ID: {{ currentUser.id }}</div>
              </div>
              <div class="quick-actions">
                <el-button-group>
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEdit(currentUser)"
                  >
                    <i class="fas fa-edit"></i> 编辑
                  </el-button>
                  <el-button
                    :type="
                      currentUser.status === 'active' ? 'danger' : 'success'
                    "
                    size="small"
                    @click="handleStatusChange(currentUser)"
                  >
                    <i
                      :class="
                        currentUser.status === 'active'
                          ? 'fas fa-ban'
                          : 'fas fa-check'
                      "
                    ></i>
                    {{ currentUser.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </el-button-group>
              </div>
            </div>

            <el-divider />

            <div class="info-grid">
              <div class="info-item">
                <div class="label">昵称</div>
                <div class="value">{{ currentUser.nickname }}</div>
              </div>
              <div class="info-item">
                <div class="label">手机号</div>
                <div class="value">{{ currentUser.phone }}</div>
              </div>
              <div class="info-item">
                <div class="label">邮箱</div>
                <div class="value">{{ currentUser.email }}</div>
              </div>
              <div class="info-item">
                <div class="label">注册时间</div>
                <div class="value">{{ currentUser.createTime }}</div>
              </div>
              <div class="info-item">
                <div class="label">最后登录</div>
                <div class="value">{{ currentUser.lastLoginTime }}</div>
              </div>
              <div class="info-item">
                <div class="label">登录IP</div>
                <div class="value">
                  {{ currentUser.lastLoginIp || "暂无记录" }}
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 统计信息 -->
        <el-tab-pane label="统计信息" name="stats">
          <div class="stats-container">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-card">
                  <div class="stat-icon">
                    <i class="fas fa-shopping-cart"></i>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ currentUser.orderCount }}</div>
                    <div class="stat-label">订单数量</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-card">
                  <div class="stat-icon">
                    <i class="fas fa-yen-sign"></i>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">
                      ¥{{ currentUser.totalSpent?.toFixed(2) || "0.00" }}
                    </div>
                    <div class="stat-label">消费总额</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-card">
                  <div class="stat-icon">
                    <i class="fas fa-star"></i>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ currentUser.reviewCount }}</div>
                    <div class="stat-label">评价数量</div>
                  </div>
                </div>
              </el-col>
            </el-row>

            <div class="activity-timeline">
              <h4>最近活动</h4>
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in currentUser.recentActivities"
                  :key="index"
                  :timestamp="activity.time"
                  :type="activity.type"
                >
                  {{ activity.content }}
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </el-tab-pane>

        <!-- 安全信息 -->
        <el-tab-pane label="安全信息" name="security">
          <div class="security-info">
            <div class="security-item">
              <div class="security-header">
                <div class="title">
                  <i class="fas fa-mobile-alt"></i>
                  手机认证
                </div>
                <el-tag
                  :type="currentUser.phoneVerified ? 'success' : 'danger'"
                >
                  {{ currentUser.phoneVerified ? "已认证" : "未认证" }}
                </el-tag>
              </div>
              <div class="security-content">
                {{ currentUser.phone || "暂未绑定手机号" }}
              </div>
            </div>

            <div class="security-item">
              <div class="security-header">
                <div class="title">
                  <i class="fas fa-envelope"></i>
                  邮箱认证
                </div>
                <el-tag
                  :type="currentUser.emailVerified ? 'success' : 'danger'"
                >
                  {{ currentUser.emailVerified ? "已认证" : "未认证" }}
                </el-tag>
              </div>
              <div class="security-content">
                {{ currentUser.email || "暂未绑定邮箱" }}
              </div>
            </div>

            <div class="security-item">
              <div class="security-header">
                <div class="title">
                  <i class="fas fa-shield-alt"></i>
                  实名认证
                </div>
                <el-tag
                  :type="currentUser.realNameVerified ? 'success' : 'danger'"
                >
                  {{ currentUser.realNameVerified ? "已认证" : "未认证" }}
                </el-tag>
              </div>
              <div class="security-content">
                {{
                  currentUser.realName ? "已完成实名认证" : "暂未进行实名认证"
                }}
              </div>
            </div>

            <div class="security-item">
              <div class="security-header">
                <div class="title">
                  <i class="fas fa-key"></i>
                  密码强度
                </div>
                <el-tag
                  :type="getPasswordStrengthTag(currentUser.passwordStrength)"
                >
                  {{ getPasswordStrengthLabel(currentUser.passwordStrength) }}
                </el-tag>
              </div>
              <div class="security-content">
                上次修改时间：{{ currentUser.lastPasswordChange || "暂无记录" }}
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 黑名单对话框 -->
    <el-dialog
      v-model="blacklistDialogVisible"
      title="加入黑名单"
      width="500px"
    >
      <el-form
        ref="blacklistFormRef"
        :model="blacklistForm"
        :rules="blacklistFormRules"
        label-width="100px"
      >
        <el-form-item label="限制类型" prop="type">
          <el-select v-model="blacklistForm.type" placeholder="请选择限制类型">
            <el-option label="临时限制" value="temporary" />
            <el-option label="永久限制" value="permanent" />
          </el-select>
        </el-form-item>
        <el-form-item label="限制时间" prop="timeRange">
          <el-date-picker
            v-model="blacklistForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-if="blacklistForm.type === 'temporary'"
          />
        </el-form-item>
        <el-form-item label="限制原因" prop="reason">
          <el-input
            v-model="blacklistForm.reason"
            placeholder="请输入限制原因"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="blacklistForm.description"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="blacklistDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBlacklistForm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

const router = useRouter();

// API接口
const API = {
  getUserList: (params) => service.get('/admin/users', { params }),
  createUser: (data) => service.post('/admin/users', data),
  updateUser: (id, data) => service.put(`/admin/users/${id}`, data),
  deleteUser: (id) => service.delete(`/admin/users/${id}`),
  batchUpdateUserStatus: (data) => service.post('/admin/users/batch-status', data),
  addToBlacklist: (data) => service.post('/admin/blacklist', data),
  removeFromBlacklist: (id) => service.delete(`/admin/blacklist/${id}`),
};

// 搜索表单
const searchForm = reactive({
  username: "",
  phone: "",
  userType: "",
  blacklistStatus: "",
  dateRange: [],
});

// 重置搜索表单
const resetSearch = () => {
  searchForm.username = "";
  searchForm.phone = "";
  searchForm.userType = "";
  searchForm.blacklistStatus = "";
  searchForm.dateRange = [];
  handleSearch();
};

// 表格数据
const loading = ref(false);
const userList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedUsers = ref([]);

// 排序配置
const sortConfig = ref({
  prop: "",
  order: "",
});

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.value = { prop, order };
  handleSearch();
};

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add");
const userFormRef = ref(null);
const userForm = reactive({
  username: "",
  nickname: "",
  phone: "",
  email: "",
  userType: "normal",
  status: "active",
});

// 详情对话框
const detailVisible = ref(false);
const currentUser = ref({});
const activeDetailTab = ref("basic");

// 黑名单对话框
const blacklistDialogVisible = ref(false);
const blacklistForm = reactive({
  userId: "",
  username: "",
  type: "temporary",
  timeRange: [],
  reason: "",
  description: "",
});

const blacklistFormRules = {
  type: [{ required: true, message: "请选择限制类型", trigger: "change" }],
  timeRange: [
    {
      required: true,
      message: "请选择限制时间",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (blacklistForm.type === "permanent") {
          callback();
        } else if (!value || value.length !== 2) {
          callback(new Error("请选择限制时间"));
        } else {
          callback();
        }
      },
    },
  ],
  reason: [{ required: true, message: "请输入限制原因", trigger: "blur" }],
};

const blacklistFormRef = ref(null);

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  userType: [{ required: true, message: "请选择用户类型", trigger: "change" }],
};

// 获取密码强度标签
const getPasswordStrengthTag = (strength) => {
  const strengthMap = {
    weak: "danger",
    medium: "warning",
    strong: "success",
  };
  return strengthMap[strength] || "info";
};

// 获取密码强度文本
const getPasswordStrengthLabel = (strength) => {
  const strengthMap = {
    weak: "弱",
    medium: "中",
    strong: "强",
  };
  return strengthMap[strength] || "未知";
};

// 搜索用户
const handleSearch = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.username || null,
      phone: searchForm.phone || null,
      userType: searchForm.userType || null,
      blacklistStatus: searchForm.blacklistStatus || null,
      startTime: searchForm.dateRange?.[0] || null,
      endTime: searchForm.dateRange?.[1] || null,
      sortBy: sortConfig.value.prop || null,
      sortOrder: sortConfig.value.order || null,
    };

    try {
      const res = await API.getUserList(params);
      console.log("获取到的用户数据:", res);
      
      // 检查返回的数据结构，后端返回的标准格式是 {code: 200, message: '操作成功', data: {list: [], total: 0}}
      if (res && res.code === 200 && res.data) {
        // 标准格式返回，从data中提取list和total
        userList.value = Array.isArray(res.data.list) ? res.data.list : [];
        total.value = res.data.total || 0;
      } else if (res && Array.isArray(res.list)) {
        // 直接返回的是list和total
        userList.value = res.list;
        total.value = res.total || 0;
      } else if (res && Array.isArray(res.data)) {
        // 直接返回的是数组
        userList.value = res.data;
        total.value = res.data.length;
      } else {
        // 空数据，显示空列表
        userList.value = [];
        total.value = 0;
        console.warn("API返回的用户数据为空或格式不正确", res);
        ElMessage.warning("没有查询到用户数据");
      }
    } catch (error) {
      console.error("API请求失败，使用测试数据", error);
      ElMessage.warning("获取数据失败，显示测试数据");
      // 测试数据
      const mockData = [
        {
          id: 1,
          username: "张三",
          nickname: "zhangsan",
          phone: "13800138001",
          email: "zhangsan@example.com",
          avatar: "/images/avatar1.jpg",
          userType: "normal",
          blacklistStatus: "normal",
          createTime: "2024-01-15 10:00:00",
          status: "active",
          lastLoginTime: "2024-03-15 15:30:00",
          lastLoginIp: "192.168.1.1",
          orderCount: 12,
          totalSpent: 2580.0,
          reviewCount: 8,
          phoneVerified: true,
          emailVerified: true,
          realNameVerified: false,
          passwordStrength: "strong",
          lastPasswordChange: "2024-02-01 14:20:00",
          recentActivities: [
            {
              time: "2024-03-15 15:30:00",
              content: "登录系统",
              type: "primary",
            },
            {
              time: "2024-03-14 10:20:00",
              content: "修改个人信息",
              type: "info",
            },
            {
              time: "2024-03-13 16:45:00",
              content: "完成订单支付",
              type: "success",
            },
          ],
        },
        {
          id: 2,
          username: "李四",
          nickname: "lisi",
          phone: "13800138002",
          email: "lisi@example.com",
          avatar: "/images/avatar2.jpg",
          userType: "merchant",
          blacklistStatus: "blacklisted",
          createTime: "2024-02-20 14:30:00",
          status: "disabled",
          lastLoginTime: "2024-03-14 09:15:00",
          lastLoginIp: "192.168.1.2",
          orderCount: 0,
          totalSpent: 0,
          reviewCount: 0,
          phoneVerified: true,
          emailVerified: false,
          realNameVerified: true,
          passwordStrength: "medium",
          lastPasswordChange: "2024-01-15 11:30:00",
          recentActivities: [
            {
              time: "2024-03-14 09:15:00",
              content: "登录系统",
              type: "primary",
            },
            {
              time: "2024-03-13 14:20:00",
              content: "账号被禁用",
              type: "danger",
            },
          ],
        }
      ];
      userList.value = mockData;
      total.value = mockData.length;
    }
  } catch (error) {
    console.error("获取用户列表失败：", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  handleSearch();
});

// 处理黑名单操作
const handleBlacklist = async (row) => {
  try {
    if (row.blacklistStatus === "blacklisted") {
      // 解除拉黑
      await ElMessageBox.confirm("确认要将该用户从黑名单中移除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });

      try {
        await API.removeFromBlacklist(row.id);
        ElMessage.success("已将用户从黑名单中移除");
        handleSearch();
      } catch (error) {
        console.error("移除黑名单失败", error);
        ElMessage.error("移除黑名单失败");
      }
    } else {
      // 加入黑名单
      blacklistForm.userId = row.id;
      blacklistForm.username = row.username;
      blacklistForm.type = "temporary";
      blacklistForm.timeRange = [];
      blacklistForm.reason = "";
      blacklistForm.description = "";
      blacklistDialogVisible.value = true;
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("操作失败：", error);
      ElMessage.error("操作失败");
    }
  }
};

// 提交黑名单表单
const submitBlacklistForm = async () => {
  if (!blacklistFormRef.value) return;

  try {
    await blacklistFormRef.value.validate();

    const data = {
      userId: blacklistForm.userId,
      type: blacklistForm.type,
      startTime:
        blacklistForm.type === "permanent" ? null : blacklistForm.timeRange[0],
      endTime:
        blacklistForm.type === "permanent" ? null : blacklistForm.timeRange[1],
      reason: blacklistForm.reason,
      description: blacklistForm.description,
    };

    try {
      await API.addToBlacklist(data);
      ElMessage.success("已将用户加入黑名单");
      blacklistDialogVisible.value = false;
      handleSearch();
    } catch (error) {
      console.error("添加黑名单请求失败", error);
      ElMessage.error("添加黑名单失败");
    }
  } catch (error) {
    console.error("表单验证失败：", error);
    ElMessage.error("表单验证失败");
  }
};

// 获取用户类型标签
const getUserTypeLabel = (type) => {
  const types = {
    normal: "普通用户",
    merchant: "商家",
    admin: "管理员",
  };
  return types[type] || type;
};

// 获取用户类型标签样式
const getUserTypeTag = (type) => {
  const types = {
    normal: "",
    merchant: "warning",
    admin: "danger",
  };
  return types[type] || "";
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 新增用户
const handleAdd = () => {
  dialogType.value = "add";
  Object.keys(userForm).forEach((key) => {
    userForm[key] = "";
  });
  userForm.userType = "normal";
  userForm.status = "active";
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = "edit";
  Object.keys(userForm).forEach((key) => {
    userForm[key] = row[key];
  });
  dialogVisible.value = true;
};

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该用户吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await API.deleteUser(row.id);
        ElMessage.success("删除成功");
        handleSearch();
      } catch (error) {
        console.error("删除用户失败", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 状态变更
const handleStatusChange = async (row) => {
  const newStatus = row.status === "active" ? "disabled" : "active";
  try {
    await API.updateUser(row.id, { status: newStatus });
    row.status = newStatus;
    const action = newStatus === "active" ? "启用" : "禁用";
    ElMessage.success(`${action}成功`);
  } catch (error) {
    console.error("更新状态失败", error);
    ElMessage.error("状态更新失败");
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return;

  try {
    await userFormRef.value.validate();
    
    try {
      if (dialogType.value === "add") {
        await API.createUser(userForm);
        ElMessage.success("添加成功");
      } else {
        await API.updateUser(userForm.id, userForm);
        ElMessage.success("更新成功");
      }
      dialogVisible.value = false;
      handleSearch();
    } catch (error) {
      console.error("保存用户数据失败", error);
      ElMessage.error(dialogType.value === "add" ? "添加失败" : "更新失败");
    }
  } catch (error) {
    console.error("表单验证失败", error);
  }
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedUsers.value = val;
};

// 批量启用
const handleBatchEnable = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning("请选择要启用的用户");
    return;
  }
  ElMessageBox.confirm(
    `确认要启用选中的 ${selectedUsers.value.length} 个用户吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    },
  ).then(async () => {
    try {
      const userIds = selectedUsers.value.map(user => user.id);
      await API.batchUpdateUserStatus({
        userIds,
        status: "active"
      });
      ElMessage.success("批量启用成功");
      handleSearch();
    } catch (error) {
      console.error("批量启用失败", error);
      ElMessage.error("批量启用失败");
    }
  });
};

// 批量禁用
const handleBatchDisable = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning("请选择要禁用的用户");
    return;
  }
  ElMessageBox.confirm(
    `确认要禁用选中的 ${selectedUsers.value.length} 个用户吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    },
  ).then(async () => {
    try {
      const userIds = selectedUsers.value.map(user => user.id);
      await API.batchUpdateUserStatus({
        userIds,
        status: "disabled"
      });
      ElMessage.success("批量禁用成功");
      handleSearch();
    } catch (error) {
      console.error("批量禁用失败", error);
      ElMessage.error("批量禁用失败");
    }
  });
};

// 导出数据
const exportData = () => {
  try {
    // 准备要导出的数据
    const exportUsers = userList.value.map(user => ({
      'ID': user.id,
      '用户名': user.username,
      '昵称': user.nickname,
      '手机号': user.phone,
      '邮箱': user.email,
      '用户类型': getUserTypeLabel(user.userType),
      '黑名单状态': user.blacklistStatus === 'blacklisted' ? '已拉黑' : '正常',
      '状态': user.status === 'active' ? '正常' : '禁用',
      '注册时间': user.createTime,
      '最后登录时间': user.lastLoginTime
    }));

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 将数据转换为工作表
    const ws = XLSX.utils.json_to_sheet(exportUsers);
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '用户列表');
    // 生成Excel文件并下载
    XLSX.writeFile(wb, `用户列表_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    ElMessage.success("数据导出成功");
  } catch (error) {
    console.error("导出数据失败", error);
    ElMessage.error("数据导出失败");
  }
};

// 显示用户详情
const showDetail = (row) => {
  currentUser.value = row;
  detailVisible.value = true;
};

// 处理头像加载失败
const handleAvatarError = (user) => {
  console.warn("头像加载失败:", user.username);
  // 设置默认头像
  user.avatar = '/images/default-avatar.png';
};
</script>

<style lang="scss" scoped>
.user-management {
  padding: 20px;

  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .list-card {
    margin-bottom: 20px;

    .toolbar {
      margin-bottom: 16px;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .right {
        display: flex;
        gap: 10px;
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .info-content {
        .username {
          font-weight: 500;
          margin-bottom: 4px;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .user-detail-dialog {
    :deep(.el-dialog__body) {
      padding: 0 20px 20px;
    }

    .user-profile {
      .profile-header {
        display: flex;
        align-items: flex-start;
        gap: 24px;
        padding: 20px 0;

        .avatar-section {
          position: relative;

          .user-status {
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            padding: 2px 12px;
            border-radius: 12px;
            font-size: 12px;
            color: white;

            &.active {
              background-color: var(--el-color-success);
            }

            &.disabled {
              background-color: var(--el-color-danger);
            }
          }
        }

        .basic-info {
          flex: 1;

          .username {
            margin: 0 0 8px;
            font-size: 24px;
          }

          .user-type {
            margin-bottom: 8px;
          }

          .user-id {
            color: var(--el-text-color-secondary);
            font-size: 14px;
          }
        }
      }

      .info-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 20px;
        padding: 20px 0;

        .info-item {
          .label {
            color: var(--el-text-color-secondary);
            margin-bottom: 8px;
            font-size: 14px;
          }

          .value {
            color: var(--el-text-color-primary);
            font-size: 16px;
          }
        }
      }
    }

    .stats-container {
      padding: 20px 0;

      .stat-card {
        background-color: var(--el-bg-color-page);
        border-radius: 8px;
        padding: 20px;
        display: flex;
        align-items: center;
        gap: 16px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          background-color: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
        }

        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: var(--el-text-color-primary);
            line-height: 1;
            margin-bottom: 8px;
          }

          .stat-label {
            font-size: 14px;
            color: var(--el-text-color-secondary);
          }
        }
      }

      .activity-timeline {
        margin-top: 30px;
        padding: 20px;
        background-color: var(--el-bg-color-page);
        border-radius: 8px;

        h4 {
          margin: 0 0 20px;
          font-size: 16px;
          color: var(--el-text-color-primary);
        }
      }
    }

    .security-info {
      padding: 20px 0;

      .security-item {
        background-color: var(--el-bg-color-page);
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;

        .security-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .title {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 16px;
            font-weight: 500;

            i {
              color: var(--el-color-primary);
            }
          }
        }

        .security-content {
          color: var(--el-text-color-secondary);
          font-size: 14px;
        }
      }
    }
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
  
  .empty-text {
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: bold;
  }
  
  .empty-subtext {
    margin-bottom: 20px;
    font-size: 14px;
    color: #909399;
  }
  
  .mt-4 {
    margin-top: 16px;
  }
}
</style>
